<template>
	<div v-loading.fullscreen.lock="loading" element-loading-text="数据导入中，请稍后...">
		<div>
			<section class="drag-section" draggable="true" @click="fileSelector.click()">
				<i class="el-icon-upload icon"></i>
				<div class="el-dragger__text">
					{{$t('message.uploadFileIntroduce')}}</em>
				</div>
				<input type="file" multiple="multiple" id="file-list" hidden="hidden" @change="fileChange" />
			</section>
			<section>
				<el-input style="width: 360px;" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入文件描述" v-model="fileDesc">
				</el-input>
			</section>
			<template v-for="(item , index) in fileList">
				<div class="file-section">
					<section class="upload-progress">
						<div :id="'progress'+index" class="bar"></div>
					</section>
					<section class="upload-infor clearfloat">
						<div class="upload-complete"><i class="el-icon-circle-check" style="color:#13ce66"></i>{{$t('message.uploadSuccess')}}</div>
						<div class="current-progress">{{$t('message.uploadProgress ')}}:&nbsp;<span>{{item.progress}}</span></div>
						<div>{{item.name}}</div>
					</section>
				</div>
			</template>
			<section style="margin-top: 15px">
				<el-button size="small" type="primary" style="float: right" @click="start">上 传</el-button>
			</section>
		</div>
	</div>
</template>
<script>
	import $ from 'jquery'
	import { GloabFun, HttpServer } from '../assets/js/common.js'
	export default {
		data() {
			return {
				loading: false,
				fileList: [],
				chunkSize: 1024 * 1024 * 20, //最大20M
				fileSelector: null,
				fileNum: 0,
				fileDesc: '',
				medias: [],
				repeatDialog: false
			};
		},
		props: {
			uploadUrl: {
				type: String,
				require: true
			},
			fileType: {
				type: Number,
				require: false
			},
			acceptTypes: {
				type: String,
				require: true
			},
			usage: {
				type: String,
				default: ' '
			},
			bandId: {
				type: Number,
				require: false
			},
		},
		methods: {
			fileChange() {
				this.fileNum = 0;
				if(this.fileSelector.files.length > 0) {
					if(this.checkFileType(this.fileSelector.files)) {
						this.fileList = this.fileSelector.files;
						$(".upload-complete").hide();
						$(".current-progress").show();
						this.beforeUpload();
					} else {
						this.fileList = [];
						//						this.$alert(this.$t('message.uploadFileLimit') + this.acceptTypes + this.$t('message.uploadFileLimit'), this.$t('message.warning'), {
						//							confirmButtonText: this.$t('message.yes'),
						//							type: 'error'
						//						});
						this.$notify.error({
							title: '错误',
							message: this.$t('message.uploadFileLimit') + this.acceptTypes + this.$t('message.uploadFileLimit'),
							duration: 2500
						});
					}
				} else {
					this.fileList = [];
				}
			},
			beforeUpload() {
				this.fileList = Array.prototype.slice.call(this.fileList);
				this.fileList.forEach(function(item, index, array) {
					item.uploadComplete = false;
					item.progress = "0%";
					item.uid = this.generateUUID();
					item.indexChunk = 0;
					item.totalChunks = Math.ceil(item.size / this.chunkSize);
					item.loadedSize = 0;
					item.index = index;
				}.bind(this));
				this.$nextTick(function() {
					this.fileList.forEach(function(item) {
						var pro = $("#progress" + item.index);
						pro.css("width", item.progress);
						pro.parents(".file-section").find(".current-progress span").text(item.progress);
					}.bind(this));
				});
				// this.loopFiles();
			},
			sliceChunk(file, fn, fn1) {
				var that = this,
					endIndex, startIndex = file.indexChunk * this.chunkSize;
				file.indexChunk++;
				if(startIndex < file.size) {
					if(startIndex + this.chunkSize >= file.size) {
						endIndex = file.size;
					} else {
						endIndex = startIndex + this.chunkSize;
					}
					var chunkFile = file.slice(startIndex, endIndex, file.type);
					/*chunkFile.name=file.name;
					chunkFile.uid=file.uid;
					chunkFile.indexChunk=file.indexChunk;
					chunkFile.totalChunks=file.totalChunks;*/
					var fd = new FormData();
					fd.append("file", chunkFile);
					/*fd.append("name", file.name);
					fd.append("uid", file.uid);
					fd.append("indexChunk", file.indexChunk);
					fd.append("totalChunks", file.totalChunks);*/
					this.startUpload(fd, file, fn, fn1);
				} else {
					//					that.$alert("上传失败，上传文件不能为空", this.$t('message.warning'), {
					//						type: 'warning'
					//					});
					that.fileList = [];
					that.$notify.error({
						title: '错误',
						message: '上传失败，上传文件不能为空',
						duration: 2500
					});
				}
			},
			onprogress(evt) {
				var file = this.fileList[this.fileNum];
				if(file.indexChunk > 1) {
					file.loadedSize = this.chunkSize * (file.indexChunk - 1) + evt.loaded;
				} else {
					file.loadedSize = evt.loaded;
				}
				var num = file.loadedSize / file.size;
				if(Math.round(num * 100) >= 100) {
					file.progress = "100%";
				} else {
					file.progress = Math.round(num * 100) + "%";
				}
				var pro = $("#progress" + file.index);
				pro.css("width", file.progress);
				pro.parents(".file-section").find(".current-progress span").text(file.progress);
			},
			start() {
				if(this.fileDesc == '') {
					this.$notify({
						title: this.$t('message.warning'),
						message: '请填写文件描述',
						type: 'warning',
						duration: 2500
					});
				} else {
					this.loopFiles();
				}
			},
			startUpload(fd, file, fn, fn1) {
				this.loading = true;
				var that = this;
				$.ajax({
					type: "POST",
					url: localHost + that.uploadUrl + "?uid=" + GloabFun.getUid() + "&token=" + GloabFun.getToken() + "&bandid=" + that.bandId + "&index=" + file.indexChunk + "&total=" + file.totalChunks + "&fileName=" + file.name + "&filetype=" + that.fileType + "&desc=" + that.fileDesc,
					data: fd,
					contentType: false,
					processData: false,
					xhr: function() {
						var xhr = $.ajaxSettings.xhr();
						if(that.onprogress && xhr.upload) {
							xhr.upload.addEventListener("progress", that.onprogress, false);
							return xhr;
						}
					},
					success: function(respon) {
						that.loading = false;
						if(respon.code === 0) {
							const h = that.$createElement;
							that.$msgbox({
								title: '导入结果',
								message: h('p', {
									style: 'word-wrap:break-word;height: 300px;overflow-y: auto'
								}, respon.description?respon.description:respon.msg),
								confirmButtonText: '确定'
							})
							// that.repeatDialog = true;
							var obj = {
								chunkAll: file.indexChunk * that.chunkSize >= file.size,
								res: respon
							};
							fn(obj);
						} else {
							file.progress = "0%";
							var pro = $("#progress" + file.index);
							pro.css("width", file.progress);
							pro.parents(".file-section").find(".current-progress span").text(file.progress);
							fn1(respon.msg);
							that.$notify.error({
								title: '错误',
								message: respon.msg,
								duration: 2500
							});
							that.fileList = [];
						}
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						that.loading = false;
						file.progress = "0%";
						var pro = $("#progress" + file.index);
						pro.css("width", file.progress);
						pro.parents(".file-section").find(".current-progress span").text(file.progress);
						that.$notify.error({
							title: '错误',
							message: '上传失败，请检查网络后重试',
							duration: 2500
						});
						//						that.$alert("上传失败，请检查网络后重试", that.$t('message.warning'), {
						//							type: 'error'
						//						});
					}
				})
			},
			loopFiles() {
				var that = this,
					p = new Promise(function(resolve, reject) {
						that.sliceChunk(that.fileList[that.fileNum], resolve, reject);
					});
				return p.then(function(res) {
					if(res.chunkAll) {
						that.medias.push(res.res.data);
						//一个文件上传完成
						var parent = $("#progress" + that.fileList[that.fileNum].index).parents(".file-section");
						parent.find(".upload-complete").show();
						parent.find(".current-progress").hide();
						if(that.fileNum < that.fileList.length - 1) {
							that.fileNum++;
							return that.loopFiles();
						} else {
							//所有文件上传完成
							that.$emit("uploadComplete", that.medias);
							//这里要清空that.fileSelector.files.length=0;
							$("#file-list").val("");
						}
					} else {
						return that.loopFiles();
					}
				}, function(msg) {
					that.fileList = [];
					that.$notify.error({
						title: '错误',
						message: msg,
						duration: 2500
					});

					//					that.$alert(msg, that.$t('message.warning'), {
					//						type: 'error'
					//					});
				});
			},
			generateUUID() {
				var d = new Date().getTime();
				var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = (d + Math.random() * 16) % 16 | 0;
					d = Math.floor(d / 16);
					return(c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
				});
				return uuid;
			},
			checkFileType(files) {
				files = Array.prototype.slice.call(files);
				var result = true;
				for(var i = 0; i < files.length; i++) {
					var fileName = files[i].name.toLowerCase();
					var fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
					if(this.acceptTypes.indexOf(fileType) === -1) {
						result = false;
						break;
					}
				}
				return result;
			}
		},
		created() {
			this.$nextTick(function() {
				this.fileSelector = document.querySelector("#file-list");
				document.addEventListener("drop", function(event) {
					event.stopPropagation();
					event.preventDefault();
				}, false);
				document.addEventListener("dragleave", function(event) {
					event.stopPropagation();
					event.preventDefault();
				}, false);
				document.addEventListener("dragenter", function(event) {
					event.stopPropagation();
					event.preventDefault();
				}, false);
				document.addEventListener("dragover", function(event) {
					event.stopPropagation();
					event.preventDefault();
				}, false);
				document.querySelector(".drag-section").addEventListener("dragover", function(event) {
					event.stopPropagation();
					event.preventDefault();
					$(this).addClass("drag-enter hover");
				}, false);
				document.querySelector(".drag-section").addEventListener("drop", function(event) {
					event.stopPropagation();
					event.preventDefault();
					this.fileNum = 0;
					$(".drag-section").removeClass("drag-enter hover");
					if(event.dataTransfer.files.length > 0) {
						if(this.checkFileType(event.dataTransfer.files)) {
							this.fileList = event.dataTransfer.files;
							$(".upload-complete").hide();
							$(".current-progress").show();
							this.beforeUpload();
						} else {
							this.fileList = [];
							this.$notify({
								title: this.$t('message.warning'),
								message: '只允许上传' + this.acceptTypes + '类型文件',
								type: 'warning',
								duration: 2500
							});
						}
					} else {
						this.fileList = [];
					}
				}.bind(this), false);
				document.querySelector(".drag-section").addEventListener("dragleave", function(event) {
					event.stopPropagation();
					event.preventDefault();
					$(this).removeClass("drag-enter hover");
				}, false);
			});
		}
	};
</script>
<style>
	.slide-fade-enter-active {
		transition: all 0.5s ease 0.5s;
		opacity: 1;
	}
	
	.slide-fade-leave-active {
		transition: all 0.5s;
		opacity: 0;
	}
	
	.slide-fade-enter {
		opacity: 0;
	}
	
	.slide-fade-leave {
		opacity: 1;
	}
</style>
<style scoped lang="less">
	.file-section {
		margin-top: 10px;
		margin-bottom: 15px;
	}
	
	.upload-complete {
		display: none;
	}
	
	.drag-section.drag-enter {
		border: 2px dashed #20a0ff;
		background-color: #fff;
	}
	
	.drag-section.hover {
		color: #20a0ff;
	}
	
	.drag-section {
		width: 360px;
		height: 180px;
		border: 1px solid #ccc;
		background-color: #f1f1f1;
		border-radius: 5px;
		text-align: center;
		cursor: pointer;
		margin-bottom: 15px;
		color: #99a9bf;
		.icon {
			font-size: 60px;
			margin-top: 40px;
		}
		&:hover {
			border-color: #20a0ff;
			color: #20a0ff;
		}
	}
	
	.upload-progress {
		width: 360px;
		height: 8px;
		.bar {
			width: 0;
			height: 8px;
			border-radius: 3px;
			background-color: #13ce66;
		}
	}
	
	.upload-infor {
		width: 360px;
		>div:not(:last-child) {
			width: 35%;
			float: left;
		}
		>div:last-child {
			text-overflow: ellipsis;
			overflow-x: hidden;
			white-space: nowrap;
			width: 65%;
			float: right;
			text-align: right;
			word-break: break-all;
			word-wrap: break-word;
		}
	}
</style>